/*

	Hernan Rivas Acosta
		hernanrivasacosta@gmail.com

	Licenced under the Mozilla Public Licence
		http://www.mozilla.org/MPL/MPL-1.1.html

	Hosted on Google Code
		http://code.google.com/p/as3localization/

*/
package org.her.localization
{
	import flash.utils.Dictionary;

	import org.her.localization.utils.parsers.IParser;

	internal class Localization
	{

		private var _langId:String;

		public function get id ():String
		{
			return _langId;
		}

		private var _dic:Dictionary;

		private var _parser:IParser;
		private var _allowParsing:Boolean;
		private var _allowOverride:Boolean;

		private var _id:int;
		private static var NEXT_ID:int = 0;

		public function Localization (parser:IParser, allowOverride:Boolean)
		{
			_id = NEXT_ID++;

			_parser = parser;
			_allowOverride = allowOverride;

			_dic = new Dictionary();
			_allowParsing = false;
		}

		public function parseXML (xml:XML):void
		{
			_allowParsing = true;
			_parser.parse(xml, addString, setId); // Passing functions as parameters exposes the API too much.
			_allowParsing = false;
		}

		private function addString (id:String, text:String):void
		{
			if (_allowParsing)
			{
				// Only override existing entries if _allowOverride is set to true.
				_dic[id] = _allowOverride || !_dic[id] ? text : _dic[id];
			}
		}

		private function setId (id:String):void
		{
			if (_allowParsing)
			{
				_langId = id;
			}
		}

		public function getString (id:String):String
		{
			return _dic[id];
		}

		public function addDefinitions (loc:Localization):void // Combines two
		{
			var a:String;

//			// Only override if both Localizations allow the feature
//			_allowOverride = _allowOverride && loc._allowOverride; // DEPRECATED

			// Override if the new data says so...
			_allowOverride = _allowOverride && loc._allowOverride;

			_allowParsing = true;
			for (a in loc._dic)
			{
				addString(a, loc._dic[a]); // add all parsed definitions.
			}
			_allowParsing = false;
		}

	}
}